package GUI;

import Interaction.ServerConnection;
import Data.Passenger;
import Flightadministration.Flightadministration;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 *
 * @author David Ponce
 * @author Philipp Armbruster
 */
public class PassengerManageAE extends JPanel {

    final Main td;
    private JPanel jp;
    public DefaultTableModel model;
    public JTable table;
    public Vector<Vector> rowData;
    public Vector<String> columnNames;
    public int currentPassengerId;
    final PassengerEdit pe;
    /*Das AdministrationsObjekt, welches über die getConnection methode vom RMI Server geholt wird, dem "admin" objekt zugewiesen.
    *Dadurch ist eine Kommunikation zwischen GUI und Applikationsserver mittels RMI möglich*/
    final Flightadministration admin = ServerConnection.getConnection();


    // Konstruktor
    public PassengerManageAE(final Main td, final PassengerEdit pe) throws RemoteException {
        this.td = td;
        this.pe = pe;
        showPassengerManageAE();
    }


    // Methoden
    public void showPassengerManageAE() throws RemoteException {

        jp = new JPanel();

        //GridBagLayout
        //**********************************************************************

        GridBagLayout gbl = new GridBagLayout();
        jp.setLayout(gbl);
        jp.setBackground(Color.white);

        GridBagConstraints constraints = new GridBagConstraints();

        constraints.fill = GridBagConstraints.HORIZONTAL;   // wie Komponente Bereich füllen soll
        constraints.weightx = 1;                     // Breite
        constraints.weighty = 1;                    // Höhe
        constraints.insets = new Insets(0,0,1,1);   // Abstände definieren


        //Label
        //**********************************************************************

        JLabel headline = new JLabel("<html><h2 color=blue>Übersicht aller Passagiere mit Nachnamen zwischen A und E</h2></html>");
        headline.setHorizontalAlignment(JLabel.CENTER);
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.gridwidth = 3;
        jp.add(headline, constraints);


        //JTable
        //**********************************************************************

        // Vector für Spaltenüberschrift mit Werten belegen
        columnNames = new Vector<String>();
        columnNames.add("ID");
        columnNames.add("Vorname");
        columnNames.add("Nachname");
        columnNames.add("Straße");
        columnNames.add("PLZ");
        columnNames.add("Wohnort");

        // Vector mit allen Airports aus DB
        rowData = admin.getAllPassengersFromAtoEForTable();

        model = new DefaultTableModel( rowData, columnNames );
        model.addTableModelListener(table);
        table = new JTable(model) {
            public boolean isCellEditable(int x, int y) {
                return false;
            }
        };
        table.setModel(model);
        table.setAutoCreateRowSorter(true);
        table.getColumnModel().getColumn(0).setPreferredWidth(10);
        table.getColumnModel().getColumn(5).setPreferredWidth(50);
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 3;
        constraints.fill = GridBagConstraints.HORIZONTAL;
    //    constraints.weighty = 1.0;
        table.setPreferredScrollableViewportSize(new Dimension(400,475));
        table.setVisible(true);
        jp.add( new JScrollPane(table), constraints);


        //Buttons
        //**********************************************************************

        JButton button_CreatePassenger = new JButton("Anlegen");
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.gridwidth = 1;
        jp.add(button_CreatePassenger, constraints);

        JButton button_EditPassenger = new JButton("Editieren");
        constraints.gridx = 1;
        constraints.gridy = 2;
        jp.add(button_EditPassenger, constraints);

        JButton button_DeletePassenger = new JButton("Löschen");
        constraints.gridx = 2;
        constraints.gridy = 2;
        jp.add(button_DeletePassenger, constraints);


        //ActionListener
        //**********************************************************************

        table.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent evt){

                //Nur auf Doppelklick der linken Mousetaste reagieren.
                if(evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() > 1){
                    edit();
                }
            }
        });
        
        button_CreatePassenger.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e) {

                ((CardLayout) td.rightp.getLayout()).show(td.rightp, "PassengerC");
            }
        });


        button_EditPassenger.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                }
                else {
                    edit();
                }
            }
        });


        button_DeletePassenger.addActionListener(new ActionListener() {
                @Override
            public void actionPerformed(ActionEvent e){
                if (table.getSelectedRow()==-1) {
                    JOptionPane.showMessageDialog(null, "Bitte ein Element der Liste auswählen!");
                }
                else {
                    int iSelectedRow = table.getSelectedRow();

                    Object[] options = {"Ja", "Nein"};
                    String txt = "<html><p style=\"color:red; text-align: center\">Passagier <i><u>"
                                    + table.getModel().getValueAt(iSelectedRow, 1)
                                    + " " + table.getModel().getValueAt(iSelectedRow, 2)
                                    + "</i></u> wirklich löschen? <br>"
                                    + "Dadurch werden auch all seine Buchungen gelöscht</p></html>";
                    int n = JOptionPane.showOptionDialog(td, txt, "Passagier löschen",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    options,
                    options[1]);
                    if (n == 0) {

                        try {
                            // Id des ausgewählten Passagiers auslesen
                            Object currentPassengerId = table.getModel().getValueAt(iSelectedRow, 0);
                                int currentPassengerIdAsInt = Integer.parseInt(currentPassengerId.toString());
                            // Vorname des Passagiers auslesen
                            Object currentFirstName = table.getModel().getValueAt(iSelectedRow, 1);
                                String currentFirstNameAsString = String.valueOf(currentFirstName);
                            // Nachname des Passagiers auslesen
                            Object currentLastName = table.getModel().getValueAt(iSelectedRow, 2);
                                String currentLastNameAsString = String.valueOf(currentLastName);
                            // Straße des Passagiers auslesen
                            Object currentStreet = table.getModel().getValueAt(iSelectedRow, 3);
                                String currentStreetAsString = String.valueOf(currentStreet);
                            // PLZ des Passagiers auslesen
                            Object currentPostcode = table.getModel().getValueAt(iSelectedRow, 4);
                                int currentPostcodeAsInt = Integer.parseInt(currentPostcode.toString());
                            // Wohnort des Passagiers auslesen
                            Object currentCity = table.getModel().getValueAt(iSelectedRow, 5);
                                String currentCityAsString = String.valueOf(currentCity);

                            // Passagierobjekt aus der Datenbank löschen
                            admin.deletePassenger(currentPassengerIdAsInt, currentFirstNameAsString, currentLastNameAsString,
                                                    currentStreetAsString, currentPostcodeAsInt, currentCityAsString);
                                // JTables aktualisieren
                                td.updatePassenger();

                            JOptionPane.showMessageDialog(null, "Passagier gelöscht!");

                        } catch (RemoteException ex) {
                            Logger.getLogger(AirportManage.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        });

    }

    public void edit() {
                    int iSelectedRow = table.getSelectedRow();
                        Object currentPassengerIdasObject = table.getModel().getValueAt(iSelectedRow, 0);
                           String currentPassengerIdAsString = String.valueOf(currentPassengerIdasObject);
                                currentPassengerId = Integer.parseInt(currentPassengerIdAsString);

                    try {
                        Passenger p = admin.getPassengerById(currentPassengerId);
                        String plz = String.valueOf(p.getPostcode());

                        String id = String.valueOf(p.getPassengerId());

                        pe.textfield1.setText(p.getLastName());
                        pe.textfield2.setText(p.getFirstName());
                        pe.textfield3.setText(p.getStreet());
                        pe.textfield4.setText(p.getCity());
                        pe.textfield5.setText(plz);
                        pe.label2.setText(id);

                        ((CardLayout) td.rightp.getLayout()).show(td.rightp, "PassengerE");

                    } catch (RemoteException ex) {
                        Logger.getLogger(PassengerManage.class.getName()).log(Level.SEVERE, null, ex);
                    }
    }
    
    public void updateTableData() throws RemoteException {

        // Vector mit Daten für JTable belegen
        rowData = admin.getAllPassengersFromAtoEForTable();

        // Tabelleninhalt wird aktualisiert
        model.setDataVector(rowData, columnNames);

    }
    public JPanel getJp() {
        return jp;
    }
}